package cn.gzjp.modules.logis.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;

import cn.gzjp.modules.gas.entity.GasRecharge;
import cn.gzjp.modules.gas.service.GasRechargeService;
import cn.gzjp.modules.it.entity.Member;
import cn.gzjp.modules.logis.entity.LogisDelivery;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import cn.gzjp.common.utils.DateUtils;
import cn.gzjp.common.utils.MyBeanUtils;
import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.common.utils.StringUtils;
import cn.gzjp.common.utils.excel.ExportExcel;
import cn.gzjp.common.utils.excel.ImportExcel;
import cn.gzjp.modules.logis.entity.LogisUser;
import cn.gzjp.modules.logis.service.LogisUserService;

/**
 * 物流用户Controller
 * @author zengcp
 * @version 2018-03-21
 */
@Controller
@RequestMapping(value = "${adminPath}/logis/logisUser")
public class LogisUserController extends BaseController {

	@Autowired
	private LogisUserService logisUserService;
	@Autowired
	private GasRechargeService gasRechargeService;
	
	
	/**
	 * 物流用户列表页面
	 */
	@RequiresPermissions("logis:logisUser:list")
	@RequestMapping(value = {"list", ""})
	public String list(LogisUser logisUser, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<LogisUser> page = logisUserService.findPage(new Page<LogisUser>(request, response), logisUser); 
		model.addAttribute("page", page);
		return "modules/logis/logisUserList";
	}

	/**
	 * 查看，增加，编辑物流用户表单页面
	 */
	@RequiresPermissions(value={"logis:logisUser:view","logis:logisUser:add","logis:logisUser:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(LogisUser logisUser, Model model) {
		model.addAttribute("logisUser", logisUser);
		return "modules/logis/logisUserForm";
	}

	/**
	 * 保存物流用户
	 */
	@RequiresPermissions(value={"logis:logisUser:add","logis:logisUser:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(LogisUser logisUser, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, logisUser)){
			return form(logisUser, model);
		}
		if(!logisUser.getIsNewRecord()){//编辑表单保存
			LogisUser t = logisUserService.get(logisUser.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(logisUser, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			logisUserService.save(t);//保存
		}else{//新增表单保存
			logisUserService.save(logisUser);//保存
		}
		addMessage(redirectAttributes, "保存物流用户成功");
		return redirect("/logis/logisUser/?repage");
	}
	
	/**
	 * 删除物流用户
	 */
	@RequiresPermissions("logis:logisUser:del")
	@RequestMapping(value = "delete")
	public String delete(LogisUser logisUser, RedirectAttributes redirectAttributes) {
		logisUserService.delete(logisUser);
		addMessage(redirectAttributes, "删除物流用户成功");
		return redirect("/logis/logisUser/?repage");
	}
	
	/**
	 * 批量删除物流用户
	 */
	@RequiresPermissions("logis:logisUser:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			logisUserService.delete(logisUserService.get(id));
		}
		addMessage(redirectAttributes, "删除物流用户成功");
		return redirect("/logis/logisUser/?repage");
	}

	/**
	 * 更新用户状态
	 */
	@RequestMapping(value = "updateStatus")
	public String updateStatus(LogisUser logisUser, int status, RedirectAttributes redirectAttributes) {
		logisUser.setStatus(status);
		logisUserService.save(logisUser);
		addMessage(redirectAttributes, "设置成功");
		return redirect("/logis/logisUser/?repage");
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("logis:logisUser:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(LogisUser logisUser, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "物流用户"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<LogisUser> page = logisUserService.findPage(new Page<LogisUser>(request, response, -1), logisUser);
    		new ExportExcel("物流用户", LogisUser.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出物流用户记录失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisUser/?repage");
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("logis:logisUser:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<LogisUser> list = ei.getDataList(LogisUser.class);
			for (LogisUser logisUser : list){
				try{
					logisUserService.save(logisUser);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条物流用户记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条物流用户记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入物流用户失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisUser/?repage");
    }
	
	/**
	 * 下载导入物流用户数据模板
	 */
	@RequiresPermissions("logis:logisUser:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "物流用户数据导入模板.xlsx";
    		List<LogisUser> list = Lists.newArrayList(); 
    		new ExportExcel("物流用户数据", LogisUser.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisUser/?repage");
    }
	@ModelAttribute
	public LogisUser get(@RequestParam(required=false) String id) {
		LogisUser entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = logisUserService.get(id);
		}
		if (entity == null){
			entity = new LogisUser();
		}
		return entity;
	}


	@RequestMapping(value = "viewRechargeLogs")
	public String viewRechargeLogs(String  unionId, Model model) {
		GasRecharge search = new GasRecharge();
		search.setUnionId(unionId);
		List<GasRecharge> recharges = gasRechargeService.findList(search);
		model.addAttribute("recharges", recharges);
		return "modules/logis/viewRechargeLogs";
	}

}